//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.jim.server.command.handler;

import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.packets.Command;
import org.jim.core.packets.Group;
import org.jim.core.packets.JoinGroupRespBody;
import org.jim.core.packets.JoinGroupResult;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.AbstractCmdHandler;
import org.jim.server.processor.group.GroupCmdProcessor;
import org.jim.server.protocol.ProtocolManager.Converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JoinGroupReqHandler extends AbstractCmdHandler {
	private static Logger log = LoggerFactory.getLogger(JoinGroupReqHandler.class);

	public JoinGroupReqHandler() {
	}

	public ImPacket handler(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
		Group joinGroup = (Group)JsonKit.toBean(packet.getBody(), Group.class);
		String groupId = joinGroup.getGroupId();
		if (StringUtils.isBlank(groupId)) {
			log.error("group is null,{}", imChannelContext);
			JimServerAPI.close(imChannelContext, "group is null when join group");
			return null;
		} else {
			GroupCmdProcessor groupProcessor = (GroupCmdProcessor)this.getSingleProcessor(GroupCmdProcessor.class);
			if (Objects.nonNull(groupProcessor)) {
				JoinGroupRespBody joinGroupRespBody = groupProcessor.join(joinGroup, imChannelContext);
				boolean joinGroupIsTrue = Objects.isNull(joinGroupRespBody) || JoinGroupResult.JOIN_GROUP_RESULT_OK.getNumber() != joinGroupRespBody.getResult().getNumber();
				if (joinGroupIsTrue) {
					joinGroupRespBody = JoinGroupRespBody.failed().setData(joinGroupRespBody);
					ImPacket respPacket = Converter.respPacket(joinGroupRespBody, imChannelContext);
					return respPacket;
				}
			}

			JimServerAPI.bindGroup(imChannelContext, joinGroup);
			return null;
		}
	}

	public Command command() {
		return Command.COMMAND_JOIN_GROUP_REQ;
	}
}
